
File name
Commit message
Commit date
File name
Commit message
Commit date
File name
Commit message
Commit date
import pandas as pd
from plotly.subplots import make_subplots
import plotly.graph_objects as go
import plotly.express as px
import plotly.io as pio
from itertools import cycle
import numpy as np
import os
df = pd.read_csv('data/2010 인구주택 총조사 기반 노인 1인가구 교육수준.csv')
index = pd.MultiIndex.from_frame(df.iloc[:,:2])
# there is a bug in pandas when its using multi index to create a DataFrame
# below is to circumvent that
# its seems you can not feed DataFrame directly and it causes pandas to create Nan values....
data = df.to_numpy()[:,-3:]
column_names = df.columns.values.tolist()
df = pd.DataFrame(data, index=index, columns=column_names[-3:])
# data and colors
columns = df.columns[2:]
palette = cycle(px.colors.qualitative.Alphabet)
# palette = cycle(px.colors.sequential.PuBu)
colors = {c:next(palette) for c in columns}
tex = index.to_list()
for i, t in enumerate(tex):
tex[i] = " ".join(t)
# subplot setup
fig = make_subplots(
rows=3, cols=1,
subplot_titles= ['계','남','여'],
vertical_spacing=0.1
)
legend = ['초졸이하', '중⋅고졸', '대졸']
c = ['#E6000F', '#FB7246', '#B3E3BE']
for chart, row in enumerate(df.groupby(level=0)):
for i, cols in enumerate(range(np.shape(data)[1])):
# groupby returns ('the name of index that has beens sliced', DataFrame)
# shouldn't that be the first thing that should be mentioned in the reference?...
tex = row[1].index.to_list()
data = row[1].to_numpy()[:,-3:]
for g, t in enumerate(tex):
tex[g] = t[1]
fig.add_trace(
go.Bar(
y=tex, # the x axis
x=data[:,i], # the value you stack
name = legend[i], #name of each bar
marker=dict(
color= c[i]
) ,
# marker_color = ['#DE4954', '#A7004C', '#57D3FC'],
# legendgroup = cols,
# marker_color = colors[cols],
showlegend = True if chart == 0 else False,
orientation = 'h'
),
row = chart+1, col = 1
)
fig.update_xaxes(range=[0,100])
fig.update_yaxes(dtick=1)
fig.update_layout(barmode='stack')
fig.update_annotations(font_size=33)
fig.update_traces(texttemplate="%{x:.2s}%", textposition='inside')
fig.update_layout(uniformtext_minsize=20, uniformtext_mode= 'hide')
fig.update_layout(
title="2010 통계청 노령인구 최종학력",
font_size= 40
)
fig.show()
pio.write_image(fig, "노령인구 최종학력.png", format="png", scale=3, width=2000, height=1200)